<template>
    <el-form-item>
        <el-button @click="onSubmit">保存</el-button>
    </el-form-item>
    <!-- 生产订单表 -->
    <h2 style="margin-left: 400px;">销售合同</h2>
    <!-- 基本信息 -->
    <div>
        <table class="order-table">
            <tr>
                <th colspan="8" style="text-align: left;">基本信息</th>
            </tr>
            <tr>
                <td style="width: 130px;">来源单据类型：</td>
                <td>
                    <el-select v-model="form.documentType" placeholder="请选择来源单据类型">
                        <el-option label="无来源" value="无来源" />
                        <el-option label="正式报价单" value="正式报价单" />
                        <el-option label="直接出库" value="直接出库" />
                        <el-option label="借货单" value="借货单" />
                        <el-option label="维修单" value="维修单" />
                        <el-option label="项目档案" value="项目档案" />
                    </el-select>
                </td>
                <td style="width: 100px;">客户名称：</td>
                <td><el-input v-model="form.clientNumber" @click="openVendors()" placeholder="请选择客户名称"/></td>
                <td style="width: 100px;"> 签约日期：</td>
                <td>
                    <el-col :span="11">
                        <el-date-picker v-model="form.agencyTime" type="date" placeholder="年月日" style="width: 200%" />
                    </el-col>
                </td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td>合同主题：</td>
                <td><el-input v-model="form.contractSubject" placeholder="请输入合同主题" /></td>
                <td>合同编号：</td>
                <td><el-input v-model="form.contractNumber" placeholder="请输入合同编号" disabled /></td>
                <td>起始日期：</td>
                <td>
                    <el-col :span="11">
                        <el-date-picker v-model="form.startTime" type="date" placeholder="年月日" style="width: 200%" />
                    </el-col>
                </td>
                <td style="width: 100px;">截止日期：</td>
                <td>
                    <el-col :span="11">
                        <el-date-picker v-model="form.endTime" type="date" placeholder="年月日" style="width: 200%" />
                    </el-col>
                </td>
            </tr>
            <tr>
                <td>我方代表：</td>
                <td><el-input v-model="form.userId"/></td>
                <td>对方代表：</td>
                <td><el-input v-model="form.clientId" @click="opencounterpart()"/></td>
                <td>合同类别：</td>
                <td>
                    <el-select v-model="form.contractCategory" placeholder="请选择合同类别">
                        <el-option label="产品订货" value="产品订货" />
                        <el-option label="经销合同" value="经销合同" />
                        <el-option label="代销合同" value="代销合同" />
                        <el-option label="承包合同" value="承包合同" />
                        <el-option label="联销合同" value="联销合同" />
                    </el-select>
                </td>
                <td>销售人员：</td>
                <td><el-input v-model="form.salespeople" /></td>
            </tr>
            <tr>
                <td>制单人员：</td>
                <td><el-input v-model="form.documentMakers" placeholder="请输入制单人员" disabled /></td>
                <td>制单日期：</td>
                <td>
                    <el-col :span="11">
                        <el-date-picker v-model="form.time" type="date" placeholder="年月日" style="width: 200%"
                            disabled />
                    </el-col>
                </td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </table>
    </div>
    <p>&nbsp;</p>
    <!-- 金额信息 -->
    <div>
        <table class="order-table">
            <tr>
                <th colspan="8" style="text-align: left;">金额信息</th>
            </tr>
            <tr>
                <td style="width: 100px;">合同总额：</td>
                <td><el-input v-model="form.contractSum" placeholder="请输入合同总额" /></td>
                <td style="width: 100px;">优惠总额：</td>
                <td><el-input v-model="form.preferentialSum" placeholder="请输入优惠总额" /></td>
                <td style="width: 110px;">优惠后总额：</td>
                <td><el-input v-model="form.preferentialAfterSum" placeholder="请输入优惠后总额" /></td>
                <td style="width: 100px;">运杂费：</td>
                <td><el-input v-model="form.after" placeholder="请输入运杂费" /></td>
            </tr>
            <tr>
                <td>收款计划：</td>
                <td>
                    <el-select v-model="form.miscellaneous" placeholder="请选择收款计划">
                        <el-option label="自动生成" value="自动生成" />
                        <el-option label="手动生成" value="手动生成" />
                    </el-select>
                </td>
                <td>开票计划：</td>
                <td>
                    <el-select v-model="form.billing" placeholder="请选择开票计划">
                        <el-option label="自动生成" value="自动生成" />
                        <el-option label="手动生成" value="手动生成" />
                    </el-select>
                </td>
                <td>开票类型：</td>
                <td>
                    <el-select v-model="form.billingType" placeholder="请选择开票类型">
                        <el-option label="明细" value="明细" />
                        <el-option label="汇总" value="汇总" />
                        <el-option label="不开票" value="不开票" />
                    </el-select>
                </td>
                <td></td>
                <td></td>
            </tr>
        </table>
    </div>
    <p>&nbsp;</p>
    <!-- 收货地址 -->
    <div>
        <table class="order-table">
            <tr>
                <th colspan="8" style="text-align: left;">收货地址</th>
            </tr>
            <tr>
                <td style="width: 100px;">收货人：</td>
                <td><el-input v-model="form.consignee" placeholder="请输入收货人"/></td>
                <td style="width: 100px;">固定电话：</td>
                <td><el-input v-model="form.landline" placeholder="请输入固定电话" /></td>
                <td style="width: 100px;">手机号码：</td>
                <td><el-input v-model="form.mobilePhone" placeholder="请输入手机号码" /></td>
                <td style="width: 100px;"></td>
                <td style="width: 100px;"></td>
            </tr>
            <tr>
                <td style="width: 100px;">详细地址：</td>
                <td colspan="7"><el-input v-model="form.fullAddress" type="textarea" placeholder="请输入详细地址" /></td>
            </tr>
            <tr>
                <td>备注：</td>
                <td colspan="7"><el-input v-model="form.remark" type="textarea" placeholder="请输入备注" /></td>
            </tr>
        </table>
    </div>
    <p>&nbsp;</p>
    <!-- 订单明细表 -->
    <div>
        <div class="header">
            <h2 style="margin-left: 400px;">采购明细</h2>
            <button @click="addNewRow">新增行</button>
        </div>
        <table>
            <thead class="order-table">
                <tr>
                    <th>序号</th>
                    <th>产品名称</th>
                    <th>产品编号</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>数量</th>
                    <th>未税单价</th>
                    <th>折扣</th>
                    <th>未税折后单价</th>
                    <th>含税单价</th>
                    <th>含税折后单价</th>
                    <th>票据类型</th>
                    <th>税率</th>
                    <th>含税折后总价</th>
                    <th>明细优惠</th>
                    <th>优惠后单价</th>
                    <th>优惠后单价（未税）</th>
                    <th>未税金额</th>
                    <th>税额</th>
                    <th>优惠后总价格</th>
                    <th>交货日期</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(row, index) in rows" :key="row.ordersId">
                    <td>{{ index + 1 }}</td>
                    <td><input v-model="row.detailsName" type="text" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.detailsNumber" type="text" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.detailsCard" type="text" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.unit" type="text" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.num" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.taxPrice" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.discount" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.discountPrice" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.taxIncludedPrice" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.taxDiscountPrice" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.bill" type="text" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.rate" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.taxDiscountSum" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.itemizedOffers" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.discountAfterPrice" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.discountAfter" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.beforeTaxPrice" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.tax" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.discountAfterSum" type="number" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.deliveryDate" type="date" style="width: 80px;" disabled /></td>
                    <td><input v-model="row.remark" type="text" style="width: 80px;" disabled /></td>
                    <td>
                        <button @click="deleteRow(row.detailsId)">删除</button>
                    </td>
                </tr>
                <tr v-if="isAdding">
                    <td>{{ rows.length + 1 }}</td>
                    <td><input v-model="newRow.detailsName" type="text" style="width: 80px;"
                            @click="openshoppingDialog()" /></td>
                    <td><input v-model="newRow.detailsNumber" type="text" style="width: 80px;" /></td>
                    <td><input v-model="newRow.detailsCard" type="text" style="width: 80px;" /></td>
                    <td><input v-model="newRow.unit" type="text" style="width: 80px;" /></td>
                    <td><input v-model="newRow.num" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.taxPrice" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.discount" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.discountPrice" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.taxIncludedPrice" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.taxDiscountPrice" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.bill" type="text" style="width: 80px;" /></td>
                    <td><input v-model="newRow.rate" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.taxDiscountSum" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.itemizedOffers" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.discountAfterPrice" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.discountAfter" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.beforeTaxPrice" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.tax" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.discountAfterSum" type="number" style="width: 80px;" /></td>
                    <td><input v-model="newRow.deliveryDate" type="date" style="width: 80px;" /></td>
                    <td><input v-model="newRow.remark" type="text" style="width: 80px;" /></td>
                    <td>
                        <button @click="saveNewRow">保存</button>
                        <button @click="cancelAddRow">取消</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- 关联产品名称 -->
    <el-dialog v-model="shoushopping" title="商品列表" width="800">
        <el-table :data="getshoppinglist" @row-click="handleshoppingRowClick">
            <el-table-column property="productsName" label="商品名称" width="150" />
            <el-table-column property="productsNumber" label="编号" width="200" />
            <el-table-column property="productsType" label="规格型号" />
            <el-table-column property="productsUnit" label="单位" />
        </el-table>
    </el-dialog>

    <!-- 关联客户名称 -->
    <el-dialog v-model="shouVendor" title="客户列表" width="800">
        <el-table :data="getVendorlist" @row-click="handleVendorRowClick">
            <el-table-column property="clientName" label="客户名称" width="150" />
            <el-table-column property="clientNumber" label="客户编号" width="200" />
            <el-table-column property="contactName" label="联系人姓名" />
            <el-table-column property="officePhone" label="办公电话" />
        </el-table>
    </el-dialog>

    <!-- 关联客户名称 
    <el-dialog v-model="Shoucounterpart" title="客户列表" width="800">
        <el-table :data="getVendorlist" @row-click="handlecounterpartRowClick">
            <el-table-column property="clientName" label="客户名称" width="150" />
            <el-table-column property="clientNumber" label="客户编号" width="200" />
            <el-table-column property="contactName" label="联系人姓名" />
            <el-table-column property="officePhone" label="办公电话" />
        </el-table>
    </el-dialog>-->

</template>

<script setup>
import { watch, ref, reactive, onMounted, toRaw } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute } from 'vue-router';
import axios from 'axios';
import router from '@/router';
import { useCounterStore } from "@/stores/counter";
import { Wread, Wwrite } from "@/axios/axiosHelper";
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue';

const route = useRoute();

const store = useCounterStore();

//产品
const shoushopping = ref(false);
//客户
const shouVendor = ref(false);
// //对方代表
// const Shoucounterpart= ref(false);

//弹出商品选择框
const openshoppingDialog = () => {
    shoushopping.value = true;
}
//弹出客户选择框
const openVendors = () => {
    shouVendor.value = true;
    console.log("打开客户选择框");
}
// //弹出对方代表选择框
// const opencounterpart = () => {
//     Shoucounterpart.value = true;
// }


// 处理表格行点击事件
const handleshoppingRowClick = (row) => {
    const id = row.productsId;
    console.log('点击行的 id 为:', id);
    // 这里可以添加你需要的其他逻辑，比如跳转到详情页等
    shoushopping.value = false;
    conditionshopping(id); // 调用条件查询商品的方法
};
// 处理表格行点击事件
const handleVendorRowClick = (row) => {
    const id = row.clientId;
    console.log('点击行的 id 为:', id);
    // 这里可以添加你需要的其他逻辑，比如跳转到详情页等
    shouVendor.value = false;
    conditionVendor(id); // 调用条件查询商品的方法
};
// // 处理表格行点击事件
// const handlecounterpartRowClick = (row) => {
//     const id = row.clientId;
//     console.log('点击行的 id 为:', id);
//     // 这里可以添加你需要的其他逻辑，比如跳转到详情页等
//     Shoucounterpart.value = false;
//     conditioncounterpart(id); // 调用条件查询商品的方法
// };

//存储条件查询出来的商品数据
const conditionshoppinglist = ref([
    {
        productsId: 0,
        productsName: "",
        productsNumber: "",
        productsType: "",
        productsUnit: "",
        productsNum: "",
        price: 0,
        remark: "",
        del: false
    }
]);

//存储条件查询出来的商品数据
const conditionVendorlist = ref([
    {
        clientId: 0,
        clientName: "",
        clientNumber: "",
        clientType: "",
        followMethods: "",
        industry: "",
        customerValue: '',
        creditRating: "",
        companyAddress: '',
        companyProfile: '',
        contactName: '',
        sex: '',
        department: '',
        birthday: '',
        office: '',
        phone: '',
        officePhone: '',
        email: '',
        qq: '',
        weChat: '',
        financialName: '',
        taxpayernumber: '',
        address: '',
        telephone: '',
        bankDeposit: '',
        account: '',
        statusCooperation: '',
        prospectsCooperation: '',
        followStrategy: '',
        del: false
    }
]);

//条件查询商品
const conditionshopping = (id) => {
    Wread.get('/w2-read/api/Products/ShowProducts', {
        params: {
            productsId: id
        }
    })
        .then(response => {
            conditionshoppinglist.value = response.data.data;
            if (conditionshoppinglist.value.length > 0) {
                const product = conditionshoppinglist.value[0];
                newRow.value.detailsName = product.productsName;
                newRow.value.detailsNumber = product.productsNumber;
                newRow.value.detailsCard = product.productsType;
                newRow.value.unit = product.productsUnit;
            }
        })
}

//条件查询商品
const conditionVendor = (id) => {
    Wread.get('/w2-read/api/Client/ShowClient', {
        params: {
            clientId: id
        }
    })
        .then(response => {
            conditionVendorlist.value = response.data.data;
            if (conditionVendorlist.value.length > 0) {
                const product = conditionVendorlist.value[0];
                form.clientNumber = product.clientName;
            }
        })
}

// //条件查询联系人
// const conditioncounterpart = (id) => {
//     Wread.get('/w2-read/api/Client/ShowClient', {
//         params: {
//             clientId: id
//         }
//     })
//         .then(response => {
//             conditionVendorlist.value = response.data.data;
//             if (conditionVendorlist.value.length > 0) {
//                 const product = conditionVendorlist.value[0];
//                 form.clientNumber = product.clientName;
//             }
//         })
// }

//弹出框的商品显示数据
const getshoppinglist = ref([
    {
        productsId: 0,
        productsName: "",
        productsNumber: "",
        productsType: "",
        productsUnit: "",
        productsNum: "",
        price: 0,
        remark: "",
        del: false
    }
]);

//弹出框的客户显示数据
const getVendorlist = ref([{
    clientId: 0,
    clientName: "",
    clientNumber: "",
    clientType: "",
    followMethods: "",
    industry: "",
    customerValue: '',
    creditRating: "",
    companyAddress: '',
    companyProfile: '',
    contactName: '',
    sex: '',
    department: '',
    birthday: '',
    office: '',
    phone: '',
    officePhone: '',
    email: '',
    qq: '',
    weChat: '',
    financialName: '',
    taxpayernumber: '',
    address: '',
    telephone: '',
    bankDeposit: '',
    account: '',
    statusCooperation: '',
    prospectsCooperation: '',
    followStrategy: '',
    del: false

}]);

//弹出框的商品显示
const getshopping = () => {
    Wread.get('/w2-read/api/Products/GetProducts')
        .then(response => {
            getshoppinglist.value = response.data.data;
        })
}
//弹出框的客户显示
const getVendor = () => {
    Wread.get('/w2-read/api/Client/GetClient')
        .then(response => {
            getVendorlist.value = response.data.data;
        })
}

onMounted(() => {
    getshopping();
    getVendor();
});

// 生成单据编号的函数
const generateDocumentsNum = () => {
    let letters = '';
    for (let i = 0; i < 4; i++) {
        letters += String.fromCharCode(65 + Math.floor(Math.random() * 26));
    }
    let numbers = '';
    for (let i = 0; i < 10; i++) {
        numbers += Math.floor(Math.random() * 10);
    }
    return letters + numbers;
};

onMounted(() => {
    // 调用生成单据编号的函数并赋值
    form.contractNumber = generateDocumentsNum();
    // 自动设置制单日期为当前系统时间
    form.time = new Date().toISOString().split('T')[0]; // 格式化为YYYY-MM-DD
});

// 销售合同表单
const form = reactive({
    saleId: 0,
    documentType: '',
    clientNumber: '',
    agencyTime: '',
    contractSubject: '',
    contractNumber: '',
    startTime: '',
    endTime: '',
    userId: '',
    clientId: '',
    contractCategory: '',
    salespeople: '',
    documentMakers: store.counterStore.userName,
    time: '',
    contractSum: '',
    preferentialSum: '',
    preferentialAfterSum: '',
    after: '',
    miscellaneous: '',
    billing: '',
    billingType: '',
    consignee: '',
    landline: '',
    mobilePhone: '',
    fullAddress: '',
    remark: '',
});

const newProcurementId = ref(0);
// 采购信息方法
const onSubmit = () => {
    Wwrite
        .post('w2-write/api/Sale/Handle', form)
        .then((res) => {
            if (res.data.code === 100) {
                newProcurementId.value = res.data.data;
                ElMessage.success(res.data.msg);
                console.log("查询销售合同单据信息数据", res.data.data);
            } else {
                ElMessage.error(res.data.msg);
            }
        })
        .catch((error) => {
            if (error.response) {
                ElMessage.error(`请求出错，状态码：${error.response.status}`);
            } else if (error.request) {
                ElMessage.error('请求已发送，但没有收到响应');
            } else {
                ElMessage.error('请求出错，请稍后重试');
            }
            console.error(error);
        });
};

// 采购明细明细数据
const rows = ref([]);
const isAdding = ref(false);
const newRow = ref({
    detailsId: '',
    detailsName: '',
    detailsNumber: '',
    detailsCard: '',
    unit: '',
    num: '',
    taxPrice: '',
    discount: '',
    discountPrice: '',
    taxIncludedPrice: '',
    taxDiscountPrice: '',
    bill: '',
    rate: '',
    taxDiscountSum: '',
    itemizedOffers: '',
    discountAfterPrice: '',
    discountAfter: '',
    beforeTaxPrice: '',
    tax: '',
    discountAfterSum: '',
    deliveryDate: '',
    remark: '',
    saleId: '',
});


// 新增行
const addRow = () => ({
    detailsId: '',
    detailsName: '',
    detailsNumber: '',
    detailsCard: '',
    unit: '',
    num: '',
    taxPrice: '',
    discount: '',
    discountPrice: '',
    taxIncludedPrice: '',
    taxDiscountPrice: '',
    bill: '',
    rate: '',
    taxDiscountSum: '',
    itemizedOffers: '',
    discountAfterPrice: '',
    discountAfter: '',
    beforeTaxPrice: '',
    tax: '',
    discountAfterSum: '',
    deliveryDate: '',
    remark: '',
    saleId: '',
});

const addNewRow = () => {
    newRow.value = addRow();
    isAdding.value = true;
    console.log("查询新增行", newRow.value);
};

const id = ref(0);

// 保存新增行
const saveNewRow = () => {
    console.log(newRow.value);
    newRow.value.saleId = newProcurementId.value;
    console.log("查询保存行", newProcurementId.value);
    Wwrite
        .post('w2-write/api/Details/CreateDetails', toRaw(newRow.value))
        .then((res) => {
            if (res.data.code === 100) {
                ElMessage.success(res.data.msg);
                rows.value.push({ ...newRow.value });
                isAdding.value = false;
                id.value = res.data.data;
                console.log("查询", id.value);
            } else {
                ElMessage.error(res.data.msg);
            }
        })
        .catch((error) => {
            if (error.response) {
                ElMessage.error(`请求出错，状态码：${error.response.status}`);
            } else if (error.request) {
                ElMessage.error('请求已发送，但没有收到响应');
            } else {
                ElMessage.error('请求出错，请稍后重试');
            }
            console.error(error);
        });
};

// 取消新增行
const cancelAddRow = () => {
    isAdding.value = false;
};



const Del = ref(0);

// 删除
const deleteRow = () => {
    console.log("删除行", id.value);
    ElMessageBox.confirm('确认删除该行？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        axios.post('https://localhost:7114/api/Details/DelDetails', {
            detailsId: id.value
        })
            .then(res => {
                if (res.data.code === 100) {
                    ElMessage.success('删除成功');
                } else {
                    ElMessage.error(res.data.msg);
                }
            })
            .catch(error => {
                if (error.response) {
                    ElMessage.error(`请求出错，状态码：${error.response.status}`);
                } else if (error.request) {
                    ElMessage.error('请求已发送，但没有收到响应');
                } else {
                    ElMessage.error('请求出错，请稍后重试');
                }
                console.error(error);
            });
    });
};
</script>

<style scoped>
.order-table {
    border-collapse: collapse;
    width: 100%;
}

.order-table th,
.order-table td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
}

.order-table th {
    background-color: #f2f2f2;
}
</style>

<style scoped>
#app {
    padding: 20px;
}
</style>